' url handlers '

import time
import logging
import hashlib
import threading
import pymysql
import reptile_service
from coroweb import get, post
from apis import Page, APIValueError, APIResourceNotFoundError, APIPermissionError
from models import Game
from config import configs

COOKIE_NAME = 'awesession'
_COOKIE_KEY = configs.session.secret


def check_admin(request):
    if request.__user__ is None or not request.__user__.admin:
        raise APIPermissionError()


def get_page_index(page_str):
    p = 1
    try:
        p = int(page_str)
    except ValueError as e:
        pass
    if p < 1:
        p = 1
    return p


def user2cookie(user, max_age):
    expires = str(int(time.time()+max_age))
    s = '%s-%s-%s-%s' % (user.id, user.passwd, expires, _COOKIE_KEY)
    L = [user.id, expires, hashlib.sha1(s.encode('utf-8')).hexdigest()]
    return '-'.join(L)


def text2html(text):
    lines = map(lambda s: '<p>%s</p>' % s.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;'), filter(lambda s: s.strip() != '', text.split('\n')))
    return ''.join(lines)


async def cookie2user(cookie_str):
    if not cookie_str:
        return None
    try:
        L = cookie_str.split('-')
        if len(L) != 3:
            return None
        uid, expires, sha1 = L
        if int(expires) < time.time():
            return None
        user = None
        if user is None:
            return None
        s = '%s-%s-%s-%s' % (uid, user.passwd, expires, _COOKIE_KEY)
        if sha1 != hashlib.sha1(s.encode('utf-8')).hexdigest():
            logging.info('invalid sha1')
            return None
        user.passwd = '******'
        return user
    except Exception as e:
        logging.info(e)
        return None


@get('/getlist')
async def getlist(*, pageNo=1, pageSize=10):
    pageStart = (int(pageNo) - 1) * int(pageSize)
    download = await Game.findAll(orderBy='game_score desc', limit=(pageStart, int(pageSize)))
    retData = {}
    retData['data'] = download
    return retData


@get('/get_all_game')
async def get_all_game():
    game = await Game.findAll()

    upperNums = 0
    insNums = 0
    lowerNums = 0
    # 0-4
    for gm in game:
        sc = int(gm['game_score'])
        if 0 < sc <= 4:
            lowerNums = lowerNums+1
        elif 4 < sc <= 7:
            insNums = insNums+1
        elif 7 < sc <= 10:
            upperNums = upperNums+1

    count = len(game)
    up = round(upperNums/count, 4)
    i = round(insNums/count, 4)
    lo = round(1 - up - i, 4)
    upper = ['7-10分', up, 'black']
    ins = ['4-7分', i, 'red']
    lower = ['0-4分', lo, 'blue']
    data = [upper, ins, lower]
    retData = {}
    retData['data'] = data
    return retData


@get('/updateList')
async def updateList():
    retData = {}
    try:
        th = threading.Thread(target=update_game)
        th.start()
        retData['code'] = 200
    except Exception as e:
        print(e)
        retData['code'] = 500
    return retData

@get('/get_game_info')
async def get_game_info(*, game_id):
    game = await Game.findAll('game_id=?', [game_id])
    retData = {}
    retData['data'] = game
    trends = reptile_service.get_line_chart_data(game_id)
    retData['trends'] = trends
    return retData


def update_game():
    game = reptile_service.get_list(1)
    db = pymysql.connect(host='localhost', user='root', password='root', port=3306, db = 'taptap')
    cur = db.cursor()
    selsql = 'select * from `tb_game` where `game_id` = %s'

    insql = 'INSERT INTO `tb_game` (`game_id`,`game_name`,`game_tab`,`game_score`,`game_date`,' \
            '`game_brief_introduction`,`game_manufacturer`)VALUES(%s,%s,%s,%s,%s,%s,%s)'

    for gm in game:
        selg = (gm['game_id'],)
        cur.execute(selsql, selg)
        result = cur.fetchone()
        if result is None:
            g = (gm['game_id'], gm['game_name'], gm['game_tab'], gm['game_score'], gm['game_date'],
                 gm['game_brief_introduction'], gm['game_manufacturer'])
            cur.execute(insql, g)
            db.commit()

    cur.close()
    db.close()
    th = threading.Thread(target=task)
    th.start()
    logging.info("task is end")


def task():
    db = pymysql.connect(host='localhost', user='root', password='root', port=3306, db='taptap')
    cur = db.cursor()
    selsql = 'select * from `tb_game` where `game_id` = %s'

    insql = 'INSERT INTO `tb_game` (`game_id`,`game_name`,`game_tab`,`game_score`,`game_date`,' \
            '`game_brief_introduction`,`game_manufacturer`)VALUES(%s,%s,%s,%s,%s,%s,%s)'

    for i in range(1000):
        url = reptile_service.splicing_url((i+1), 10)
        print(url)
        ls = reptile_service.get_soup(url)
        for l in ls:
            if l.get('type') == ('default'):
                des_url = 'https://www.taptap.com'
                des_url = des_url+l.get('web_url')
                logging.info("game_id is " + str(l.get('app_summary').get('id')))
                gamesDetail = reptile_service.agame(des_url)
                gamesDetail['game_id'] = l.get('app_summary').get('id')
                gamesDetail['game_name'] = l.get('title')
                gamesDetail['game_score'] = l.get('rating').get('score')

                selg = (gamesDetail['game_id'],)
                cur.execute(selsql, selg)
                result = cur.fetchone()
                if result is None:
                    g = (gamesDetail['game_id'], gamesDetail['game_name'], gamesDetail['game_tab'], gamesDetail['game_score'], gamesDetail['game_date'],
                         gamesDetail['game_brief_introduction'], gamesDetail['game_manufacturer'])
                    cur.execute(insql, g)
                    db.commit()
                    logging.info('获取到新数据('+str(g[0])+','+g[1]+')')
    cur.close()
    db.close()

